// ActionScript file
import com.octlan.equationgraph.base.Constants;
import com.octlan.equationgraph.ctrl.MainCtrl;
import com.octlan.equationgraph.model.Operator;
import com.octlan.equationgraph.model.OperatorCategory;
import com.octlan.equationgraph.util.XMLHelper;

import flash.events.MouseEvent;
import flash.external.ExternalInterface;
import flash.utils.Dictionary;

import mx.collections.ArrayCollection;
import mx.controls.Image;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;

private function init():void
{
    loadOperators();
}

private var category:String = null;
private function showMenuHandler(event:MouseEvent):void
{
    var image:Image = event.currentTarget as Image;
    myTA.text = image.toolTip;
    category = image.toolTip;
    operationMenu.source = image.source;
    operationMenu.move(image.x, operationMenu.y);

}

private function mouseMoveHandler(event:MouseEvent):void
{
    var image:Image = event.currentTarget as Image;
    myTA.text = "x=" + event.localX + "y= " + event.localY;

}
private function mouseDownHandler(event:MouseEvent):void
{
    if (category == "matrix") // matrix需要输入参数
    {

    }
    var x:uint = event.localX;
    var y:uint = event.localY;
    var str:String = generateCmdStr(x, y);
    var cursor:int = cmd.selectionBeginIndex;
    var prefix:String = cmd.text.substring(0, cmd.selectionBeginIndex);
    var postfix:String = cmd.text.substring(cmd.selectionEndIndex, cmd.text.length);
    cmd.text = prefix + str + postfix;
    var pos:int = getCursorPosition(x, y, str.length);
    cursor = cursor + pos;
    cmd.setSelection(cursor, cursor);

}
private function getCursorPosition(x:uint, y:uint, len:uint):int
{
    var result:int = len;
    var oc:OperatorCategory = opcMap[category];
    var xindex:uint = x / (oc.itemwidth + oc.itemhorzitonalgap);
    var yindex:uint = y / (oc.itemheight + oc.itemverticalgap);
    for each (var item:Operator in oc.itemlist)
    {
        if (xindex == item.xindex && yindex == item.yindex)
        {
            if (item.cursor < 0)
            {
                result = len + item.cursor;
            }
            else if (item.cursor == Constants.MAX_CMD_LENGTH)
            {
                reuslt = len;
            }
            else
            {
                result = item.cursor;
            }
            break;
        }
    }
    return result;
}

private function generateCmdStr(x:uint, y:uint):String
{
    var result:String = "";
    var oc:OperatorCategory = opcMap[category];
    var xindex:uint = x / (oc.itemwidth + oc.itemhorzitonalgap);
    var yindex:uint = y / (oc.itemheight + oc.itemverticalgap);
    for each (var item:Operator in oc.itemlist)
    {
        if (xindex == item.xindex && yindex == item.yindex)
        {
            result = item.value;
            break;
        }
    }
    return result;
}
private function generateImage():void
{
    var str:String = "gif";

    str = Constants.SERVER_URI + "?" + cmd.text;
    str = encodeURI(str);
    ExternalInterface.call("getImage", str);
}

private var cs:HTTPService;
private function loadOperators():void
{
    var ctrl:MainCtrl = MainCtrl.getInstance();
    cs = ctrl.createService();
    cs.url = Constants.CONFIG_URI;
    cs.addEventListener(ResultEvent.RESULT, onOperationResult);

    var paras:URLVariables = new URLVariables();
    paras.filename = 'operations.xml';

    cs.send(paras);
}
[Bindable]
private var opcMap:Dictionary = null;

private function onOperationResult(event:ResultEvent):void
{
    cs.removeEventListener(ResultEvent.RESULT, onOperationResult);
    cs = null;

    opcMap = null;
    opcMap = new Dictionary();
    var str:String = event.result.toString();
    var info:XML = XMLHelper.removeNamespaceURI(str);
    for each (var item:XML in info.children())
    {
        var oc:OperatorCategory = new OperatorCategory();
        oc.id = item.@id;
        oc.name = new String(item.name);
        oc.cname = new String(item.cname);
        oc.itemcols = parseInt(item.itemcols);
        oc.itemrows = parseInt(item.itemrows);
        oc.itemwidth = parseInt(item.itemwidth);
        oc.itemheight = parseInt(item.itemheight);
        oc.itemverticalgap = parseInt(item.itemverticalgap);
        oc.itemhorzitonalgap = parseInt(item.itemhorzitonalgap);
        oc.itemlist = makeOperationList(item.itemlist);
        opcMap[oc.id] = oc;
    }
    trace(opcMap);
}
private function makeOperationList(il:XMLList):ArrayCollection
{
    var result:ArrayCollection = new ArrayCollection();
    for each (var item:XML in il.children())
    {
        var op:Operator = new Operator();
        op.name = new String(item.name);
        op.cname = new String(item.cname);
        op.value = new String(item.value);
        op.xindex = parseInt(item.xindex);
        op.yindex = parseInt(item.yindex);
        op.cursor = parseInt(item.cursor);
        result.addItem(op);
    }
    return result;
}


private function getImageData():void
{
    var url:String = Constants.SERVER_URI;
    url = url + '?pictype=gif&latex=' + encodeURIComponent(cmd.text);

    //resultImage.load(url);
    ExternalInterface.call("getImage", url);
}


